package com.l.web.service.webcontent;

import com.l.web.service.system.webnode.WebNodeDAO;
import com.l.web.service.system.webnode.WebNodeOptionDAO;
import org.l.qiao.Cluster;
import org.l.qiao.ClusterUtil;
import org.l.qiao.Validate;
import org.l.qiao.search.Query;
import org.l.qiao.search.Sort;
import com.l.web.service.ServiceSupport;
import com.l.web.service.system.webnode.WebNodeOption;
import org.apache.log4j.Logger;

import java.util.List;

public class WebContentDetailService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(WebContentDetailService.class);
    private WebContentDAO webContentDAO;
    private WebNodeDAO webNodeDAO;
    private WebNodeOptionDAO webNodeOptionDAO;

    public void setWebContentDAO(WebContentDAO webContentDAO) {
        this.webContentDAO = webContentDAO;
    }

    public void setWebNodeDAO(WebNodeDAO webNodeDAO) {
        this.webNodeDAO = webNodeDAO;
    }

    public void setWebNodeOptionDAO(WebNodeOptionDAO webNodeOptionDAO) {
        this.webNodeOptionDAO = webNodeOptionDAO;
    }

    public String execute() {
        String type = form.getString(TYPE);
        String result = "";

        switch (type) {
            case "save":
                result = save();
                break;
            default:
                result = detail();
        }

        return result;
    }

    public String detail() {
        String webNodeId = form.getString("webNodeId");
        String id = form.getString("id");
        LOGGER.debug("webNodeId=" + webNodeId + ",id=" + id);

        if (Validate.check(Validate.OBJECTID, webNodeId) && (id == null || Validate.check(Validate.OBJECTID, id))) {
            Query contentQuery = new Query();
            contentQuery.idEQ(WebContent.WEB_NODE_ID, webNodeId);

            if (id != null) {
                contentQuery.idEQ(id);
            }

            Cluster webContent = webContentDAO.findOne(contentQuery);

            if (webContent.isEmpty()) {
                LOGGER.error("所查看的栏目内容不存在");
                error(404);
                return NONE;
            }

            Query optionQuery = new Query();
            optionQuery.idEQ(webNodeId);
            Sort sort = new Sort();
            sort.asc(WebNodeOption.INDEX);
            List webNodeOptions = webNodeOptionDAO.find(optionQuery, null, sort);

            context.put("webContent", webContent);
            context.put("webNodeOptions", webNodeOptions);
            context.put("check", ClusterUtil.getCheck(WebContent.class));
            return DETAIL;
        } else {
            error(404);
            LOGGER.error("错误参数：webNodeId=" + webNodeId + ",id=" + id);
            return NONE;
        }
    }

    public String save() {
        return NONE;
    }

}
